<?php
/**
 * Created by IntelliJ IDEA.
 * User: fang.cai.liang@aliyun.com
 * Date: 2017/7/3
 * Time: 15:51
 */

namespace nflow;


class Utils
{
    // 移动运营商 的号码段
    private static $mobile_no_segment = ['134', '135', '136', '137', '138', '139', '147', '150', '151', '152', '157', '158', '159',
'178', '182', '183', '184', '187', '188', '1705'];

    // 电信运营商 的号码段
    private static $telecom_no_segment = ['133', '153', '173', '177', '180', '181', '189', '1700'];

    // 联通运营商 的号码段
    private static $unicom_no_segment = ['130', '131', '132', '145', '155', '156', '175', '176', '185', '186', '1709'];

    /**
     * 电话号码校验
     * @param $phone
     * @return bool
     * @throws \Exception
     */
    public static function isPhone($phone){
        $exp = "/^(13|14|15|17|18)[0-9]{9}$/";
        if(preg_match($exp, $phone)){
            return true;
        }
        throw new \Exception('电话号码不合法!', 10001);
    }

    /**
     * 根据电话号码 获取是属于哪一个运营商
     * @param $phone
     * @return int|null
     */
    public static function getOperator($phone){
        if(self::isMobileOperator($phone)){
            return OPERATOR_ID_MOBILE;
        }
        if(self::isUnicomOperator($phone)){
            return OPERATOR_ID_UNICOM;
        }
        if(self::isTelecomOperator($phone)){
            return OPERATOR_ID_TELECOM;
        }
        return null;
    }

    /**
     * 判断手机号是不是移动的
     * @param $phone
     * @return bool
     */
    public static function isMobileOperator($phone){
        return self::isSpecifiedOperator($phone, self::$mobile_no_segment);

    }

    /**
     * 判断手机号是不是电信的
     * @param $phone
     * @return bool
     */
    public static function isTelecomOperator($phone){
        return self::isSpecifiedOperator($phone, self::$telecom_no_segment);

    }

    /**
     * 判断手机号是不是联通的
     * @param $phone
     * @return bool
     */
    public static function isUnicomOperator($phone){
        return self::isSpecifiedOperator($phone, self::$unicom_no_segment);

    }

    /**
     * @param $phone
     * @param array $operatorList
     * @return bool
     */
    public static function isSpecifiedOperator($phone, Array $operatorList){
        $first3Num = substr($phone, 0, 3);
        if(in_array($first3Num, $operatorList) || in_array(substr($phone, 0, 4), $operatorList)){
            return true;
        }
        return false;
    }
}